<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';

import { Button, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getUserActions, type UserActionsData } from '#/api/user/actions';
import Icon from '#/components/Icons';

import { FormModalView } from './components';

defineOptions({
  name: 'UserAdminUserAction',
});

const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const cycleTypes: any = { 0: '不限', 1: '天', 2: '小时', 3: '永久' };
const gridOptions: VxeGridProps<UserActionsData> = {
  rowConfig: {
    isHover: true,
  },
  pagerConfig: {
    enabled: false,
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { field: 'name', title: '操作名称' },
    { field: 'score', title: '积分更改' },
    { field: 'coin', title: '金币更改' },
    { field: 'cycle', title: '奖励次数/周期', slots: { default: 'cycle' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const { data } = await getUserActions();
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const openDialog = async (
  title: '新增' | '编辑',
  row?: null | UserActionsData,
) => {
  formModalApi.setState({
    title: `${title}${viewTitle}`,
  });
  formModalApi.setData(row);
  formModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <Grid :table-title="`${viewTitle}列表`">
      <template #cycle="{ row }">
        <div>
          <span v-show="row.cycle_type === 1 || row.cycle_type === 2">
            {{ row.reward_number }}次/{{ row.cycle_time }}
            {{ cycleTypes[row.cycle_type] }}
          </span>
          <span v-show="row.cycle_type === 0 || row.cycle_type === 3">
            {{ cycleTypes[row.cycle_type] }}
          </span>
        </div>
      </template>

      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog('编辑', row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            编辑
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
